package com.faxsun.validation;

import org.apache.commons.validator.GenericValidator;
import org.broadleafcommerce.core.web.controller.account.UpdateAccountForm;
import org.broadleafcommerce.core.web.controller.account.validator.UpdateAccountValidator;
import org.broadleafcommerce.profile.core.domain.Customer;
import org.broadleafcommerce.profile.web.core.CustomerState;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

import com.faxsun.profile.core.service.FSCustomerService;

public class FSUpdateAccountValidator extends UpdateAccountValidator {
	
	@Override
	public void validate(UpdateAccountForm form, Errors errors) {

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "emailAddress", "emailAddress.required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "firstName.required");
        
        if (!errors.hasErrors()) {

            //is this a valid email address?
            if (!GenericValidator.isEmail(form.getEmailAddress())) {
                errors.rejectValue("emailAddress", "emailAddress.invalid");
            }

            //check email address to see if it is already in use by another customer
            Customer customerMatchingNewEmail = customerService.readCustomerByEmail(form.getEmailAddress());
            int sameEmailNum=((FSCustomerService)customerService).countCustomerByEmail(form.getEmailAddress());

            if (customerMatchingNewEmail != null && !CustomerState.getCustomer().getId().equals(customerMatchingNewEmail.getId()) || sameEmailNum>1) {
            	//email已被用户使用且当前用户id与查询到的用户id不同或者前面条件满足的情况下，相同email的用户>1
                //customer found with new email entered, and it is not the current customer
                errors.rejectValue("emailAddress", "emailAddress.used");
            }
            
        }
        
    }
	
}
